# -*- coding:utf8 -*- #
# -----------------------------------------------------------------------------------
# ProjectName:  smart-meter-iot-test-console
# FileName:     mqttConnect.py
# Author  :     
# Datetime:     2023/4/7 23:46
# Description：MQTT连接
# -----------------------------------------------------------------------------------
from time import sleep

from paho.mqtt import client as mqtt_client
from common.util.configUtil.configUtil import ConfigUtil
from common.util.jsonUtl.jsonUtil import JsonUtil
from common.util.logUtil.logUtil import LoggerUtil
from common.util.timeUtil.timeUtil import get_timestamp
from core.mqtt.libProject.get_device_secret.getDeviceSecret import get_device_secret

logger = LoggerUtil()


def mqtt_connect(deviceName: str):
    mqttPassword = None
    mqttHostUrl = None
    readJson = JsonUtil()
    conf = ConfigUtil()
    mqttHostPort = conf.get_mqtt_config("mqttHostPort")

    # 当连接上服务器后回调此函数
    def on_connect(client, userdata, flags, rc) -> None:
        connectResult = readJson.read_connack(rc)
        if rc == 0:
            print(f"MQTT{connectResult}")
        else:
            print(f"MQTT连接失败,失败原因:{connectResult}")

    mqttUserName = conf.get_mqtt_config("mqttUserName").format(deviceName, productKey)
    # MQTT链接ID
    mqttClientId = conf.get_mqtt_config("mqttClientId").format(deviceName)
    # 通过ID链接MQTT
    getDeviceSecretJson, url = get_device_secret(deviceName, timestamp)
    if getDeviceSecretJson:
        if getDeviceSecretJson["success"] is False:
            print("请输入正确的设备号段！")
        elif getDeviceSecretJson["success"] is True:
            if "test" or "192" in url:
                print('……开始连接测试环境……')
            else:
                print('……开始连接生产环境,请谨慎操作！……')
            mqttPassword = getDeviceSecretJson["data"]["password"]
            mqttHostUrl = getDeviceSecretJson["data"]["mqttUrl"]
            print(f"mqttlientId:{mqttClientId}")
            print(f"mqttUserName:{mqttUserName}")
            print(f"mqttPassword:{mqttPassword}")
            print(f"mqttUrl:{mqttHostUrl}")
    client = mqtt_client.Client(client_id=mqttClientId)
    client.username_pw_set(mqttUserName, mqttPassword)
    client.connect(mqttHostUrl, int(mqttHostPort), keepalive=300)
    client.on_connect = on_connect
    client.on_message = on_message
    return client


# publish (发布)消息
def on_publish(client, topic, payload) -> None:
    client.publish(topic, payload)


def on_message(client, msg):
    topic = msg.topic
    if "rrpc/request" in topic:
        synchronousMessage = f"同步消息接收{msg.topic}:{str(msg.payload)}"
        print(synchronousMessage)
        topic = f"/sys/{productKey}/{deviceName}/thing/service/DeviceControlSync:DeviceControl_reply"
        on_publish(client, topic, '{"ResultCode":200,"ResultMsg":"操作成功"}')
        print("响应结束！")
    else:
        synchronousMessage = f"异步消息接收{msg.topic}:{str(msg.payload)}"
        print(synchronousMessage)


if __name__ == '__main__':
    conf = ConfigUtil()
    deviceName = conf.get_mqtt_config("deviceName")
    productKey = conf.get_productkey()
    # run(deviceName, productKey, get_timestamp())
